<template>
    <div v-if="flowDirectionList" class="chart_content pdt_12 pdl_12 pdr_12">
        <zt-echart ref="echart" :opts="opts"></zt-echart>
    </div>
</template>

<script setup lang="ts">
import { ZtEchart } from "@ztstory/datav-core";
import type { FlowDirectionItem } from "@/model/model";
import { computed, onUnmounted, ref } from "vue";
import {
    BarDirectionEnum,
    createBarOpts,
    createBarSeriesItem,
    createGradientColors,
} from "@ztstory/datav-core/echarts-opts";
interface Props {
    flowDirectionList?: FlowDirectionItem[];
}

const props = defineProps<Props>();

const echart = ref();
const intervalId: number | undefined = undefined;

const categorys: string[] = [];
const values: string[] = [];

// 最小轮播值
const minLoopLimit = 8;
// 最小间隔时间
const minInterval = 2;

// 开始动态数据展示
const startDynamicData = () => {
    const datas = props.flowDirectionList?.reverse();
    if (!datas || datas.length <= minLoopLimit) {
        return;
    }
    let index = minLoopLimit + 1;
    setInterval(() => {
        categorys.shift();
        values.shift();
        if (index >= datas.length) {
            index = 0;
        }

        categorys.push(datas[index].target);
        values.push(datas[index].count);

        echart.value?.updateOptions({
            yAxis: {
                data: categorys,
            },
            series: {
                data: values,
            },
        });

        index++;
    }, minInterval * 1000);
};

// 计算图表选项
const opts = computed(() => {
    // 清除之前的定时器
    clearInterval(intervalId);
    // 清空类别和数值数组
    categorys.length = 0;
    values.length = 0;

    try {
        // 遍历流向列表，初始化类别和数值数组
        props.flowDirectionList?.reverse().forEach((item, index) => {
            if (index >= minLoopLimit) {
                // 超过最小轮播值时停止遍历
                throw false;
            }
            categorys.push(item.target);
            values.push(item.count);
        });
    } catch (error) {}

    // 开启动态数据展示
    startDynamicData();

    // 创建柱状图选项
    const barOpts = createBarOpts(
        [createGradientColors(["#239BFF", "#49D6FF"])], // 创建渐变颜色
        categorys, // 设置类别数据
    );
    // 设置系列数据
    barOpts.series = [createBarSeriesItem(values, BarDirectionEnum.Horizontal)];
    // 设置网格配置
    barOpts.grid = {
        top: 0,
        bottom: 0,
        left: 0,
        right: 25,
        containLabel: true,
        height: "100%",
    };
    return barOpts; // 返回配置选项
});

// 组件卸载时清除定时器
onUnmounted(() => {
    clearInterval(intervalId);
});
</script>

<style scoped lang="less">
.chart_content {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
}
</style>
